package com.rc.saas.tenant.controller.order;

import com.alibaba.excel.EasyExcel;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageInfo;
import com.rc.saas.tenant.base.TenantBaseController;
import com.rc.saas.tenant.base.WebPageInfo;
import com.rc.saas.tenant.common.constant.CommonConstant;
import com.rc.saas.tenant.common.redis.RedisLoader;
import com.rc.saas.tenant.common.utils.StringUtil;
import com.rc.saas.tenant.common.vo.StdRequest;
import com.rc.saas.tenant.common.vo.TResponse;
import com.rc.saas.tenant.model.elec.ElecGun;
import com.rc.saas.tenant.model.elec.ElecStation;
import com.rc.saas.tenant.model.fault.RcElecPileFaultRecord;
import com.rc.saas.tenant.model.hlht.HlhtOperator;
import com.rc.saas.tenant.model.hlht.HlhtOperatorExample;
import com.rc.saas.tenant.model.hlht.HlhtTenantOpen;
import com.rc.saas.tenant.model.hlht.HlhtTenantOpenExample;
import com.rc.saas.tenant.model.hlhtsk.HlhtskTenant;
import com.rc.saas.tenant.model.member.MemberInfo;
import com.rc.saas.tenant.model.operator.RcOperator;
import com.rc.saas.tenant.model.order.OrderInfo;
import com.rc.saas.tenant.model.order.OrderRefundApply;
import com.rc.saas.tenant.model.rc.RcOperatorAccount;
import com.rc.saas.tenant.model.tenant.*;
import com.rc.saas.tenant.search.enterprise.EnterpriseSubMemberApplySearch;
import com.rc.saas.tenant.model.tenant.*;
import com.rc.saas.tenant.search.fault.RcElecPileFaultRecordSearch;
import com.rc.saas.tenant.search.order.HlhtOrderInfoSearch;
import com.rc.saas.tenant.search.order.OrderRefundApplySearch;
import com.rc.saas.tenant.search.order.OrderSearch;
import com.rc.saas.tenant.search.order.OrderTotalDataSearch;
import com.rc.saas.tenant.service.elec.ElecGunService;
import com.rc.saas.tenant.service.elec.ElecStationService;
import com.rc.saas.tenant.service.hlht.HlhtOperatorService;
import com.rc.saas.tenant.service.hlht.HlhtTenantOpenService;
import com.rc.saas.tenant.service.hlhtsk.HlhtskTenantService;
import com.rc.saas.tenant.service.member.MemberInfoService;
import com.rc.saas.tenant.service.operator.RcOperatorService;
import com.rc.saas.tenant.service.order.OrderInfoService;
import com.rc.saas.tenant.service.order.OrderRefundApplyService;
import com.rc.saas.tenant.service.tenant.TenantCompanyInfoService;
import com.rc.saas.tenant.service.tenant.TenantRoleService;
import com.rc.saas.tenant.service.tenant.TenantService;
import com.rc.saas.tenant.shiro.ShiroUtils;
import com.rc.saas.tenant.util.ExportUtils;
import com.rc.saas.tenant.util.PubFetchTool;
import com.rc.saas.tenant.vo.hlht.HlhtTenantVo;
import com.rc.saas.tenant.vo.order.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;


@Controller
@RequestMapping("/orderRefundApply")
public class OrderRefundApplyController extends TenantBaseController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private OrderRefundApplyService orderRefundApplyService;

    @Autowired
    private TenantRoleService tenantRoleService;


    /**
     * 跳转申请退款列表
     *
     * @return
     */
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String orderInfoPage(Model model) {
        return "/templates/order/orderRefundApply";

    }

    /**
     * 数据权限过滤
     * @param search
     * @return
     */
    protected OrderRefundApplySearch dataAuth(OrderRefundApplySearch search){
        //获取登陆人信息
        TenantUser user = getSessionTenantUser();
        TenantRole tenantRole = tenantRoleService.selectByPrimaryKey(user.getTenantRoleId());
        String dataAuth = tenantRole.getDataAuth();//数据权限 100 平台权限, 010 加盟商权限,001企业权限,111全部权限 默认111 不能为000
        String roleType = tenantRole.getRoleType();//角色类型 ( 0 超级管理员 1 普通用户 2加盟商 3企业用户) 默认1
        search.setDataAuth(dataAuth);
        search.setRoleType(roleType);
        search.setBaseOperatorId(user.getOperatorId());

        if ("3".equals(tenantRole.getRoleType())){
            //企业用户
            search.setEnterpriseId(user.getEnterpriseId());
        }else if ("2".equals(tenantRole.getRoleType())){
            //加盟商
            search.setOperatorId(user.getOperatorId());
        }else if ("1".equals(tenantRole.getRoleType())){
            //自定义角色
            if (tenantRole.getDataAuth().endsWith("0")){
                //如果不查询企业会员置0
                search.setEnterpriseId(0L);
            }
            /*if ("100".equals(tenantRole.getDataAuth())){
                //查询自营
                search.setEnterpriseId(0L);
            }else if("010".equals(tenantRole.getDataAuth())){

            }else if("001".equals(tenantRole.getDataAuth())){

            }else if("100".equals(tenantRole.getDataAuth())){

            }else if("100".equals(tenantRole.getDataAuth())){

            }*/
        }
        return search;
    }

    /**
     * 退款申请列表-返回订单列表数据
     *
     * @return
     */
    @RequestMapping(value = "/listOrderRefund", method = RequestMethod.GET)
    @ResponseBody
    public WebPageInfo listOrderRefund(OrderRefundApplySearch orderRefundApplySearch) {
        //数据权限
        dataAuth(orderRefundApplySearch);

        PageInfo<OrderRefundApplyVo> pageInfo = orderRefundApplyService.listOrderRefund(orderRefundApplySearch);
        WebPageInfo webPageInfo = new WebPageInfo(pageInfo.getList(), Long.valueOf(pageInfo.getTotal()).intValue());
        return webPageInfo;
    }

    /**
     * 保存审核
     *
     * @param orderRefundApplyId
     * @return
     */

    @RequestMapping(value = "/updateStatus", method = RequestMethod.POST)
    @ResponseBody
    public TResponse updateStatus(Long orderRefundApplyId, String status, String remark) {
        TenantUser user = ShiroUtils.getSessionUser();
        Date date = new Date();
        OrderRefundApply info = orderRefundApplyService.selectByPrimaryKey(orderRefundApplyId);
        if (info == null) {
            return TResponse.FAIL("入参错误");
        }
        info.setLastUpdatedBy(user.getLoginName());
        info.setLastUpdatedTime(date);
        info.setAuditingTime(date);
        //退款申请
        int code = orderRefundApplyService.updateStatus(orderRefundApplyId, status, remark);
        if (code==0){
            return TResponse.FAIL("操作失败");
        }
        return TResponse.SUCCESS();
    }

    /**
     * 导出退款申请列表数据
     */
    @ResponseBody
    @RequestMapping("/exporListOrderRefund")
    public TResponse exporListOrderRefund(OrderRefundApplySearch search, HttpServletResponse response) {
        response.setHeader("Set-Cookie", "fileDownload=true; path=/");
        try {
            ExportUtils.setDefaultPaging(search);
            //数据权限
            dataAuth(search);
            PageInfo<OrderRefundApplyVo> pageInfo = orderRefundApplyService.listOrderRefund(search);
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("退款申请列表", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            EasyExcel.write(response.getOutputStream(), OrderRefundApplyVo.class).sheet("退款申请列表").doWrite(pageInfo.getList());
            return TResponse.SUCCESS();
        } catch (Exception e) {
            logger.error("导出失败", e.getMessage());
            return TResponse.FAIL(e.getMessage());
        }
    }


}
